
package com.enjoyiot.module.bms.sevice.asset;

import com.enjoyiot.framework.common.pojo.PageResult;
import com.enjoyiot.framework.common.util.object.BeanUtils;
import com.enjoyiot.module.bms.controller.admin.asset.vo.AssetCreateReqVO;
import com.enjoyiot.module.bms.controller.admin.asset.vo.AssetPageReqVO;
import com.enjoyiot.module.bms.controller.admin.asset.vo.AssetUpdateReqVO;
import com.enjoyiot.module.bms.dal.dataobject.AssetDO;
import com.enjoyiot.module.bms.dal.mysql.asset.AssetMapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.List;
import java.util.stream.Collectors;

import static com.enjoyiot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.enjoyiot.module.bms.enums.ErrorCodeConstants.ASSET_NOT_EXISTS;

@Service
@Validated
public class AssetServiceImpl implements AssetService {

    @Resource
    private AssetMapper assetMapper;

    @Override
    public Long createAsset(AssetCreateReqVO createReqVO) {
        // 插入
        AssetDO asset = BeanUtils.toBean(createReqVO, AssetDO.class);
        assetMapper.insert(asset);
        // 返回
        return asset.getId();
    }

    @Override
    public void updateAsset(AssetUpdateReqVO updateReqVO) {
        // 校验存在
        validateAssetExists(updateReqVO.getId());
        // 更新
        AssetDO updateObj = BeanUtils.toBean(updateReqVO, AssetDO.class);
        assetMapper.updateById(updateObj);
    }

    @Override
    public void deleteAsset(Long id) {
        // 校验存在
        validateAssetExists(id);
        // 删除
        assetMapper.deleteById(id);
    }

    private void validateAssetExists(Long id) {
        if (assetMapper.selectById(id) == null) {
            throw exception(ASSET_NOT_EXISTS);
        }
    }

    @Override
    public AssetDO getAsset(Long id) {
        return assetMapper.selectById(id);
    }

    @Override
    public PageResult<AssetDO> getAssetPage(AssetPageReqVO pageReqVO) {
        return assetMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateAssetStatus(Long id, Integer status) {
        // 校验用户存在
        validateAssetExists(id);
        // 更新状态
        AssetDO updateObj = new AssetDO();
        updateObj.setId(id);
        updateObj.setStatus(status);
        assetMapper.updateById(updateObj);
    }

    @Override
    public List<AssetDO> getSimpleAssetList(String assetName) {
        return assetMapper.selectSimpleList(assetName);
    }

}
